package org.filehanding.service;

import org.filehanding.dao.FileMapper;
import org.filehanding.entity.FileHanding;
import org.filehanding.entity.User;
import org.filehanding.util.PropertiesUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * Created by liguo on 2016/5/14.
 */
@Service
public class FileService {
    @Autowired
    private FileMapper fileMapper;

    /**
     * 上传文件
     *
     * @param file
     * @param user
     */
    public void addfile(MultipartFile file, User user) {
        //取得文件上传根路径
        String path = PropertiesUtil.getFileUploadPath()+File.separator+user.getName();
        //获取文件名
        String fileName = file.getOriginalFilename();
        File targetFile = new File(path, fileName);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }

        //保存
        try {
            file.transferTo(targetFile);
            FileHanding fileHanding = new FileHanding();
            fileHanding.setGuid(UUID.randomUUID().toString());
            fileHanding.setUserGuid(user.getGuid());
            fileHanding.setFileName(fileName);
            fileHanding.setFileSize(file.getSize());
            fileMapper.insert(fileHanding);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 列出上传文件列表
     *
     * @param userGuid
     * @return
     */
    public List<FileHanding> getByUserGuid(String userGuid) {
        return fileMapper.selectByUserGuid(userGuid);
    }

    /**
     * 取得下载文件列表
     *
     * @param user
     * @return
     */
    public List<FileHanding> listDownloadFiles(User user) {
        File dir = new File(PropertiesUtil.getFileDownloadPath() + File.separator + user.getName());
        if (!dir.exists()) {
            dir.mkdirs();
        }

        File[] files = dir.listFiles();
        if (files == null) {
            return null;
        }
        List<FileHanding> list = new ArrayList<FileHanding>();
        for (int i = 0; i < files.length; i++) {
            if (!files[i].isDirectory()) {
                FileHanding fileHanding = new FileHanding();
                fileHanding.setFileName(files[i].getName());
                fileHanding.setFileSize(files[i].length());
                fileHanding.setCreatedTime(new Date(files[i].lastModified()));
                list.add(fileHanding);
            }
        }
        return list;
    }

    /**
     * 下载文件
     *
     * @param fileGuid
     * @return
     */
    public FileHanding getFile(String fileGuid) {
        FileHanding fileHanding = fileMapper.selectByGuid(fileGuid);
        return fileHanding;
    }
}
